// 引入mockjs
import Mock from "mockjs";
import _ from "lodash";

const random = Mock.Random;

const translateUrl = function (url) {
  let arr = url.split("?")[1].split("&"); //先通过？分解得到？后面的所需字符串，再将其通过&分解开存放在数组里
  let obj = {};
  for (let i of arr) {
    obj[i.split("=")[0]] = i.split("=")[1]; //对数组每项用=分解开，=前为对象属性名，=后为属性值
  }
  return obj;
};

const responseData = {
  success: true,
  data: Object,
  msg: null,
};

// 拦截ajax请求，配置mock的数据

const userTmp = {
  id: "@id",
  userName: "@word",
  name: "@cname",
  pwd: "@pwd",
  tel: "13514741241",
  hospitalId: "@increment(1)",
  hospitalName: "@province 第一医院",
  "role|1": ["manager", "doctor", "expert"],
};

Mock.mock("/myapi/account/login", "post", (req) => {
  const { userName, pwd } = JSON.parse(req.body);
  console.log("login", userName, pwd);
  const result = { ...responseData };
  if (userName) {
    result.data = {
      user: Mock.mock(userTmp),
      token: random.guid(),
    };
  } else {
    result.success = false;
    result.msg = "username is missing!";
  }
  return result;
});

Mock.mock("/myapi/account/changePwd", "put", (req) => {
  const { pwd, confirmPwd } = JSON.parse(req.body);
  console.log("修改密码", pwd, confirmPwd);
  const result = { ...responseData };
  if (pwd !== confirmPwd) {
    result.success = false;
    result.msg = "确认密码错误";
  }
  return result;
});

/** -------------医院------------ */
Mock.mock(/\/myapi\/hospital\/list/, "get", (req) => {
  const { page, size } = translateUrl(req.url);
  console.log("医院列表");
  const result = { ...responseData };
  result.success = true;
  const total = 124;
  let list = [];

  if (page * size < total) {
    for (let i = (page - 1) * size; i < page * size; i++) {
      list.push({
        id: i,
        area: random.province(),
        name: `${random.city()}第一医院`,
        level: random.integer(1, 3),
      });
    }
  } else {
    if ((page - 1) * size < total) {
      for (let i = (page - 1) * size; i < total; i++) {
        list.push({
          id: i,
          area: random.province(),
          name: `${random.city()}第一医院`,
          level: random.integer(1, 3),
        });
      }
    }
  }

  result.data = {
    list,
    total,
  };
  return result;
});

/** -------------用户------------ */
Mock.mock(/\/myapi\/user\/list/, "get", (req) => {
  const { page, size } = translateUrl(req.url);
  console.log("用户列表", page, size);
  const result = { ...responseData };
  result.success = true;
  const total = 24;

  let list = [];
  const tmp = {};
  if (page * size < total) {
    tmp[`array|${size}`] = [userTmp];
  } else {
    if ((page - 1) * size < total) {
      const sub = total - (page - 1) * size;
      tmp[`array|${sub}`] = [userTmp];
    }
  }

  list = Mock.mock(tmp).array;

  result.data = {
    list,
    total,
  };
  return result;
});

console.log("%c前端 mock 环境启动成功", "color: #38f;font-weight: bold");

export default Mock;
